package rpcbiz

import (
	"net"
	"fmt"
	"github.com/astaxie/beego/logs"
	"cloud_worm/util/unet/rpc"
	"time"
	"crypto/tls"
)

type RpcServer struct {
	Address 	string
	PemFile		string
	KeyFile 	string

	l 			net.Listener
}

func (r *RpcServer) RpcServe() error {
	rpc.DefaultServer.Debug = true
	rpc.DefaultServer.ReadTimeout = 30 * time.Second
	rpc.DefaultServer.WriteTimeout = 30 * time.Second

	//rpc.DefaultServer = &rpc.Server{
	//	Debug: true,
	//	ReadTimeout: 30 * time.Second,
	//	WriteTimeout: 5 * time.Second,
	//}
	//rpc.Register(new(WeaponEvent))
	//rpc.Register(new(WolAgentEvent))
	rpc.Register(new(rpc.Heartbeat))

	if r.l != nil {
		return fmt.Errorf("rpc server is already stated")
	}
	// 加载证书
	cert, err := tls.LoadX509KeyPair(r.PemFile, r.KeyFile)
	if err != nil {
		return err
	}
	config := &tls.Config{Certificates: []tls.Certificate{cert}}

	r.l, err = tls.Listen("tcp", r.Address, config)
	if err != nil {
		return err
	}

	go func() {
		for {
			conn, err := r.l.Accept()
			if err != nil {
				logs.Error("rpc.Server accept: ", err.Error())
				continue
			}

			go rpc.ServeConn(conn)
		}
	}()

	return nil
}
